<template>
  <Card title="字段标签配置" :bordered="false" :head-style="headStyle" :loading="loading" class="field-tag-config">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" @click="handleSave"> 保存 </a-button>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'move'">
          &#9769
        </template>
        <template v-if="column.key === 'field'">
          <Select
:options="formGetFieldsData" v-model:value="record[column.key]" class="w-[100%]"
               optionFilterProp="label" showSearch
              />
        </template>
        <template v-if="column.key === 'cond'">
          <a-button
:type="record[column.key] && record[column.key].length ? 'primary' : 'default'"
            @click="handleConfiguration(column.key, index)">
            <SettingOutlined title="配置" />
          </a-button>
        </template>
        <template v-if="column.key === 'isTag'">
          <Switch v-model:checked="record[column.key]" checked-children="是" un-checked-children="否" />
        </template>
        <template v-if="column.key === 'color'">
          <ColorPicker format="rgba" v-model:value="record[column.key]" />
        </template>
      </template>
      <template #action="{ index }">
        <TableAction
:actions="[
          {
            icon: 'ant-design:delete-outlined',
            tooltip: '删除',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              placement: 'left',
              confirm: handleDelete.bind(null, index),
            },
          },
        ]" />
        <div></div>
      </template>
    </BasicTable>
    <ConfigurationModal
@register="registerModalConfiguration" @success="handleSuccessConfiguration"
      popupContainer=".field-tag-config" />
  </Card>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, nextTick } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useMessage } from '/@/hooks/web/useMessage';
import { Card, Switch } from 'ant-design-vue';
import { getVisualGetFieldProps, getVisualUpdateFieldProps } from '/@/api/module/module';
import ColorPicker from '/@/components/ColorPicker/src/ColorPicker.vue';
import ConfigurationModal from '../../configuration/index';
import { useModal } from '/@/components/Modal';
import { SettingOutlined } from '@ant-design/icons-vue';
import {Select} from 'ant-design-vue'

export default defineComponent({
  // eslint-disable-next-line vue/component-definition-name-casing
  components: {
    BasicTable,
    TableAction,
    Card,
    Switch,
    ColorPicker,
    ConfigurationModal,
    SettingOutlined,
    Select
  },
  props: {
    moduleCode: {
      type: String,
      default: '',
    },
    headStyle: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formGetFieldsData: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  },
  setup(props) {
    const { createMessage } = useMessage();
    const loading = ref(false);
    const getVisualGetFieldPropsData = async () => {
      const res = await getVisualGetFieldProps({ moduleCode: props.moduleCode });
      const data = res.fieldProps ? JSON.parse(res.fieldProps) : [];
      setTableData(data);
    };
    const fetch = async () => {
      nextTick().then(() => {
        getVisualGetFieldPropsData();
      });
    };
    onMounted(fetch);

    const columns = ref([
      {
        title: '',
        dataIndex: 'seq',
        width: 50,
        ellipsis: true,
        resizable: false,
        key: 'move',
        customCell: () => {
          return {
            style: {
              cursor: 'move',
            },
          };
        },
      },
      {
        title: '字段',
        dataIndex: 'field',
        key: 'field',
        width: 200,
      },
      {
        title: '条件',
        dataIndex: 'cond',
        key: 'cond',
        width: 100,
      },
      {
        title: '颜色',
        dataIndex: 'color',
        key: 'color',
      },
      {
        title: '是否 Tag',
        dataIndex: 'isTag',
        key: 'isTag',
      },
    ]);

    const [registerTable, { reload, setProps, getDataSource, setTableData }] = useTable({
      title: '',
      api: getVisualGetFieldProps,
      columns,
      formConfig: {
        labelWidth: 120,
        schemas: [],
        autoSubmitOnEnter: true,
      },
      useSearchForm: false,
      showTableSetting: false,
      showIndexColumn: true,
      immediate: false,
      searchInfo: {
        moduleCode: props.moduleCode,
      }, //额外的参数
      // afterFetch: (data) => {
      //   console.log('data', data);
      //   const newData = data;
      //   if (isArray(newData)) {
      //     newData.forEach((item) => {

      //     });
      //     setTableData(newData);
      //   }
      // },
      bordered: true,
      indexColumnProps: { width: 50 },
      canResize: false,
      rowKey: 'id',
      actionColumn: {
        width: 200,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: undefined,
      },
      customRow: customRow,
    });

    const dataSource = ref([]);
    let source = 0; // 源目标数据序号
    let target = 0; // 目标数据序号
    // Table行拖拽
    function customRow(record, index) {
      return {
        props: {
          // draggable: 'true'
        },
        style: {
          // cursor: 'pointer',
        },
        // 鼠标移入
        onMouseenter: (event) => {
          // event.srcElement.tagName始终为TR，无法区分是点在了哪一列
        },
        onMousedown: (event) => {
          console.log('event', event);
          event.stopPropagation();
          console.log('event', event.srcElement.tagName);
          if (event.srcElement.tagName === 'TD') {
            let cellIndex = event.srcElement.cellIndex;
            console.log('cellIndex', cellIndex);
            // 如果点击的是第1列（第0列为复选框列），则使可以拖动
            // 因拖拽会影响拷贝粘贴，故限制只能在第1列可拖拽
            if (cellIndex == 1) {
              event.target.draggable = true; // 使可以拖动
            }
          }
        },
        // 开始拖拽
        onDragstart: (event) => {
          // 兼容IE
          let ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到源目标数据序号
          source = index;
          console.log(record, index, 'source');
          dataSource.value = getDataSource();
        },
        // 拖动元素经过的元素
        onDragover: (event) => {
          // 兼容 IE
          let ev = event || window.event;
          // 阻止默认行为
          ev.preventDefault();
        },
        // 鼠标松开
        onDrop: (event) => {
          // 兼容IE
          let ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到目标数据序号
          target = index;
          const dataFrom = dataSource.value[source];
          dataSource.value.splice(source, 1);
          dataSource.value.splice(target, 0, dataFrom);
          console.log('dataSource', dataSource.value);
          setTableData(dataSource.value);
          // event.target.parentElement.draggable = false; // 取消拖动
          // console.log(record, index, 'target', source, target);
        },
        onDblclick: () => { },
        onClick: (ev) => {
          console.log('onClick', ev);
          ev.stopPropagation();
        },
      };
    }

    //新增
    const handleCreate = () => {
      console.log('getDataSource', getDataSource());
      let data = getDataSource() || [];
      data.push({ cond: '', isTag: true, color: '' });
      setTableData(data);
    };

    async function handleDelete(index) {
      try {
        let data = getDataSource() || [];
        data.splice(index, 1);
        setTableData(data);
      } catch (err) {
        console.error(err);
      } finally {
        handleSetProps(false);
      }
    }

    let currentIndex = 0;
    const [registerModalConfiguration, { openModal: openConfiguration }] = useModal();
    //配置
    const handleConfiguration = (field, index) => {
      currentIndex = index;
      let data = getDataSource() || [];
      openConfiguration(true, {
        type: field,
        list: data[currentIndex][field] || [],
        formGetFieldsData: props.formGetFieldsData,
      });
    };
    //配置回调
    const handleSuccessConfiguration = ({ field, value }) => {
      console.log('handleSuccessConfiguration', value);
      let data = getDataSource() || [];
      data[currentIndex][field] = value;
      setTableData(data);
    };

    function handleSuccess() {
      getVisualGetFieldPropsData();
    }

    const handleSetProps = (bool: boolean) => {
      setProps({ loading: bool });
    };

    const handleSave = async () => {
      const data = getDataSource() || [];
      console.log('data', data);
      try {
        const params = {
          fieldProps: data.length ? JSON.stringify(data) : '',
          moduleCode: props.moduleCode,
        };
        handleSetProps(true);
        await getVisualUpdateFieldProps(params);
        createMessage.success('操作成功');
        handleSuccess();
      } catch (err) {
        console.error(err);
      } finally {
        handleSetProps(false);
      }
    };

    return {
      registerTable,
      handleDelete,
      handleSuccess,
      handleCreate,
      loading,
      handleSave,
      registerModalConfiguration,
      handleConfiguration,
      handleSuccessConfiguration,
    };
  },
});
</script>
<style scoped>
:deep(.ant-table-cell) {
  overflow: visible !important;
}

:deep(.ant-table-content) {
  overflow: unset !important;
}
</style>
